using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using MEC;
using UniFramework.Event;

public class UITransitionTween : MonoBehaviour
{
    public Image LoadingImg;
    public GameObject ParentGOBJ;
    
    private Vector3 EnterPoint,OutPoint;
    private float LiveTime;// 如果存在时间小于1秒，那就在loadingout时候等待一下，不然闪一下很难受

    public bool isLoadinDone = false;

    private readonly EventGroup _eventGroup = new EventGroup();
    private void Awake()
    {
        DontDestroyOnLoad(this.transform.parent.gameObject);
        

    }
    void Start()
    {
        EnterPoint = new Vector3(ParentGOBJ.transform.localPosition.x, 0, 0);
        OutPoint = new Vector3((ParentGOBJ.transform.localPosition.x - 10000), 0, 0);
        
        LiveTime = Time.time;
        Timing.RunCoroutine(LoadingIn());
        _eventGroup.AddListener<UILoadEventDefines>(OnLoadComplete);
    }


    IEnumerator<float> LoadingIn()
    {
        yield return Timing.WaitForOneFrame;
        LoadingImg.transform.DOLocalMove(EnterPoint, 1).OnComplete(()=>
        {
            isLoadinDone = true;
        });
    }

    

    IEnumerator<float> LoadingOutIE()
    {
        float elapsedtime = Time.time - LiveTime;
        if (elapsedtime <= 1)
            yield return Timing.WaitForSeconds(1);
        else
            yield return Timing.WaitForOneFrame;

        if (LoadingImg != null)
        {
            LoadingImg.transform.DOLocalMove(OutPoint, 1).OnComplete(() =>
            {
                Destroy(this.gameObject);
            });
        }
    }

    public void LoadingOut()
    {
        Timing.RunCoroutine(LoadingOutIE());
    }

    private void OnLoadComplete(IEventMessage msg)
    {
        if (msg is UILoadEventDefines)
        {
            this.LoadingOut();
        }
    }
}
